package com.webSite.demo.cy.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class FileUtils {
	private static final String endpoint = "http://oss-cn-beijing.aliyuncs.com";
	private static final String accessKeyId = "LTAI5t1TiVl1ZWN0";
	private static final String accessKeySecret = "oTBU8yJnnyWYRKSfAwEclsSnP2v7Zl";
	private static final String bucketName = "fzh";
	private static final String KEY_STRING = "http://fzh.oss-cn-beijing.aliyuncs.com/";
	private static OSSClient ossClient;

	public FileUtils() {
		ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
	}

	public String upload(String fileName,File file) throws Exception {
		ossClient.putObject(bucketName, fileName, file);

		ossClient.shutdown();

		return getUrl(fileName);
	}
	
	public String uploadToInputStream(String fileName,InputStream inputStream) {
		ossClient.putObject(bucketName,fileName, inputStream);
		return KEY_STRING+fileName;
	}

	public void delete(String keyName) {
		ossClient.deleteObject(bucketName, keyName);
	}

	public List<String> delList(String images) {
		DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest("fzh").withKeys(imagesName(images)));
		List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
		return deletedObjects;
	}

	public static String getUrl(String key) {
		Date expiration = new Date(new Date().getTime() + 315360000000L);
		String urlString = "";
		URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
		if (url != null) {
			urlString = url.toString();
			urlString = urlString.substring(0, urlString.indexOf("?"));
			return urlString;
		}
		return null;
	}

	public static List<String> imagesName(String key) {
		String[] images = key.split(",");
		List<String> keys = new ArrayList<String>();
		for (String img : images) {
			img = img.replace(KEY_STRING, "");
			img = img.substring(0, img.indexOf("?"));
			keys.add(img);
		}
		return keys;
	}
	
	
}
